import { defineStore, storeToRefs } from "pinia";
import { ref } from "vue";
//import { usePersistStore, userGroupStore } from "@/stores";
import { useDeskStore, usePersistStore, useShortStore } from "@/stores";
//表格数据读取相关
import * as XLSX from "xlsx";
import { readFileAsBinaryString } from "@/utils/readFile";
import { changeArr, getInfo, testStr } from "@/utils/function";
import {
  addTobaccoBasicService,
  delTobaccoService,
  //downLoadService,
  getTobaccoBasicInfoService,
  getTobaccoDetailInfoService,
  getTobaccoListService,
  modifyTobaccoInfoService,
  modifyTobaccoDetailService,
  modifyTobaccoBasicService,
  showPlaceService,
  uploadDetaiInfoService,
  tobaccoShortService,
  tobaccoRecommendService,
} from "@/api/tobaccoApi";
import { ElMessage } from "element-plus";

export const useTobaccoStore = defineStore("tobacco", () => {
  const persistStore = usePersistStore();
  const deskStore = useDeskStore();
  const { getAllRfids, getAvailableRfids } = deskStore;
  //const groupStore = userGroupStore();
  //const { groupTobaccoList, groupTobaccoTotal } = storeToRefs(groupStore);
  const { tobaccoList, tobTotal, userInfo, shortList } =
    storeToRefs(persistStore);

  //单料烟的条件查询
  const queryData = ref({
    page: 1,
    pageSize: 5,
    year: "",
    location: "",
    part: "",
    evaluate: "",
  });
  const loading = ref(false);
  //单料烟分页查询请求
  const gettobaccos = async () => {
    loading.value = true;
    const res = await getTobaccoListService(queryData.value);
    tobaccoList.value = res.data.rows;
    tobTotal.value = res.data.total;
    loading.value = false;
  };
  if (userInfo.value.token != "") {
    gettobaccos();
  }
  //单料烟查询表单的清空
  const clearQueryData = () => {
    queryData.value = {
      page: 1,
      pageSize: 5,
      year: null,
      location: "",
      part: "",
      evaluate: "",
    };
    //groupTobaccoList.value = [];
    //groupTobaccoTotal.value = 0;
    gettobaccos();
  };
  //单料烟查询表单的提交
  const submitQuery = () => {
    queryData.value.page = 1;
    queryData.value.pageSize = 5;
    gettobaccos();
  };

  //单料烟分页相关
  const tobSizeChange = (pageSize) => {
    queryData.value.pageSize = pageSize;
    queryData.value.page = 1;
    gettobaccos();
  };
  const tobPageChange = (page) => {
    queryData.value.page = page;
    gettobaccos();
  };

  //单料烟的多选查找(电子标签)
  const tobTable = ref();
  let rfids = []; //存放多选的电子标签值
  let ids = []; //存放多选的id
  const multipleChoice = (value) => {
    rfids = [];
    value.forEach((item) => {
      rfids.push(item.rfid);
      ids.push(item.id);
    });
  };
  // 单料烟的查找位置的显示
  const showTobaccoPlace = ref(false);
  //根据rfid号查找到的详细信息
  const rfidInfo = ref([]);
  //单料烟位置查找请求
  const showplace = async () => {
    const res = await showPlaceService(rfids);
    rfidInfo.value = [];
    ids = [];
    rfids = [];
    rfidInfo.value = res.data;
    console.log(rfidInfo.value);
    ElMessage.success("查找成功");
  };
  const searchByrfids = () => {
    showTobaccoPlace.value = true;
    showplace();
    tobTable.value.clearSelection();
  };

  //单料烟备注的编辑
  const infoChecked = ref([]);
  const infoCheckedChange = () => {};
  const commentVisible = ref(false);
  const id = ref();
  const changeComment = (row) => {
    commentVisible.value = true;
    id.value = row.id;
  };
  //关闭备注的对话框
  const closeDialog = () => {
    infoChecked.value = [];
    commentVisible.value = false;
  };
  //单料烟备注修改请求
  const modifyTobaccoInfo = async (data) => {
    const res = await modifyTobaccoInfoService(data);
    gettobaccos();
    ElMessage.success(res.message);
  };
  //提交备注信息
  const submitComment = () => {
    if (infoChecked.value.length !== 0) {
      const tempInfo = getInfo(infoChecked.value);
      //将需要传递的参数存储为数组
      const temp = {
        id: id.value,
        info: tempInfo,
      };
      modifyTobaccoInfo(temp);
    }
    closeDialog();
  };
  //单料烟信息删除
  const delTobacco = async (data) => {
    const res = await delTobaccoService(data);
    ElMessage.success(res.message);
    gettobaccos();
    getAvailableRfids();
    // getOverview();
    // getYearData();
    // getLocationData();
  };
  //单料烟的删除
  const tobDelete = (index, row) => {
    ElMessageBox.confirm("你确定要删除这条信息吗?", "温馨提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        delTobacco(row);
      })
      .catch(() => {
        ElMessage.success("取消删除");
      });
  };
  //单料烟的详细信息(根据id请求获得的)
  const detailInfo = ref({
    priority: ["", ""], //优先级
  });
  //单料烟编辑和查询
  const drawerTitle = ref("");
  const drawerVisible = ref(false);
  const isSearch = ref(false);
  const num = ref(0); //1表示查找,2表示编辑
  const searchIndex = ref(0); //记录需要编辑或查找的单料烟id，用于发送请求
  //单料烟的推荐
  const replace = async (index, row) => {
    drawerVisible.value = true;
    drawerTitle.value = "单料烟推荐";
    num.value = 1;
    isSearch.value = true;
    searchIndex.value = row.id;
    const res = await getTobaccoDetailInfoService(row.id);
    Object.keys(res.data).forEach((key) => {
      detailInfo.value[key] = res.data[key];
    });
  };

  //单料烟详细信息的编辑
  const tobEdit = async (index, row) => {
    drawerVisible.value = true;
    drawerTitle.value = "单料烟详细信息编辑";
    num.value = 2;
    isSearch.value = false;
    searchIndex.value = row.id;
    console.log(row.id);
    const res = await getTobaccoDetailInfoService(row.id);
    Object.keys(res.data).forEach((key) => {
      detailInfo.value[key] = res.data[key];
    });
  };
  //单料烟详细信息编辑和查询的提交
  const submitEvent = async () => {
    //TODO:开始单料烟编辑或查询的请求
    if (num.value === 1) {
      const res = await tobaccoRecommendService(detailInfo.value);
      console.log(detailInfo.value);
      ElMessage.success(res.message);
    } else {
      const res = await modifyTobaccoDetailService(detailInfo.value);
      ElMessage.success(res.message);
    }
    drawerVisible.value = false;
    console.log(detailInfo.value);
  };
  //单料烟的基本信息的单条添加和编辑
  const addForm = ref();
  const addTitle = ref();
  const addDrawerVisible = ref(false);
  const isAddTob = ref(false);
  const baseIndex = ref();
  const tempInfo = ref();
  const addTobaccoData = ref({
    id: "",
    rfid: null,
    name: "",
    location: "",
    year: "",
    part: "",
    evaluate: null,
    info: "",
  });
  const addTobaccRules = {
    id: [{ required: true, message: "请输入单料烟名称", trigger: "blur" }],
    name: [{ required: true, message: "请输入单料烟名称", trigger: "blur" }],
    location: [
      { required: true, message: "请输入单料烟产地", trigger: "blur" },
    ],
    rfid: [{ required: true, message: "请选择单料rfid号", trigger: "change" }],
    year: [
      { required: true, message: "请输入单料烟年份", trigger: "blur" },
      { pattern: /^\d{4}$/, message: "请输入正确的年份", trigger: "blur" },
    ],
    part: [{ required: true, message: "请输入单料烟名称", trigger: "blur" }],
    evaluate: [
      { required: true, message: "请选择单料烟评估状态", trigger: "change" },
    ],
  };
  //添加表单的清空
  const clearAddData = () => {
    addTobaccoData.value = {
      id: "",
      rfid: null,
      name: "",
      location: "",
      year: "",
      part: "",
      evaluate: null,
      info: "",
    };
    infoChecked.value = [];
  };
  //单料烟基本信息修改请求
  const modifyTobacco = async () => {
    const res = await modifyTobaccoBasicService(addTobaccoData.value);
    gettobaccos();
    ElMessage.success(res.message);
  };
  //单料烟基本信息添加请求
  const addTobaccoBasic = async () => {
    const res = await addTobaccoBasicService(addTobaccoData.value);
    //更新数据
    gettobaccos();
    getAvailableRfids();
    // getOverview();
    // getYearData();
    // getLocationData();
    ElMessage.success(res.message);
  };
  const addTobacco = () => {
    addDrawerVisible.value = true;
    isAddTob.value = true;
    addTitle.value = "添加单料烟";
    clearAddData();
  };
  //根据单料烟id获取基本信息请求
  const getbasicInfo = async (id) => {
    const res = await getTobaccoBasicInfoService(id);
    addTobaccoData.value = res.data;
  };

  //单料烟基本信息的编辑
  const baseTobEdit = (index, row) => {
    addDrawerVisible.value = true;
    addTitle.value = "单料烟基本信息编辑";
    baseIndex.value = index;
    //编辑需要回显
    addTobaccoData.value = getbasicInfo(row.id);
    isAddTob.value = false;
  };

  //单料烟基本信息单条添加的提交
  const submitAddTobacco = async () => {
    await addForm.value.validate();
    if (isAddTob.value) {
      addTobaccoBasic();
    } else {
      tempInfo.value = tobaccoList.value[baseIndex.value].info;
      if (infoChecked.value.length != 0) {
        addTobaccoData.value.info = getInfo(infoChecked.value);
      }
      modifyTobacco();
    }

    addDrawerVisible.value = false;
    infoChecked.value = [];
    clearAddData();
  };

  //============================================================================
  // 表格数据的上传
  const uploadTableData = ref([]);
  const baseTableData = ref([]); //基本数据
  const detailTableData = ref([]); //详细数据
  const baseData = ref(0); //用于区分基础信息1还是详细信息0

  //单料烟数据的导入
  const uploadDraw = ref(false);
  const openUploadDraw = () => {
    uploadTableData.value = ref([]);
    baseTableData.value = ref([]);
    detailTableData.value = ref([]);
    uploadDraw.value = true;
    drawerTitle.value = "单料烟信息导入";
  };

  //更改详细信息表传入的字段名
  const characters = {
    column1: { text: "序号", type: "string" },
    column2: { text: "rfid号", type: "string" },
    column3: { text: "物料号", type: "string" },
    column4: { text: "批次", type: "string" },
    column5: { text: "物料描述", type: "string" },
    column6: { text: "等级类别", type: "number" },
    column7: { text: "干草香", type: "number" },
    column8: { text: "清甜香", type: "number" },
    column9: { text: "正甜香", type: "number" },
    column10: { text: "焦甜香", type: "number" },
    column11: { text: "青香", type: "number" },
    column12: { text: "木香", type: "number" },
    column13: { text: "焦香", type: "number" },
    column14: { text: "辛香", type: "number" },
    column15: { text: "丰富度", type: "number" },
    column16: { text: "香气状态", type: "number" },
    column17: { text: "香型类型", type: "string" },
    column18: { text: "香型程度", type: "number" },
    column19: { text: "浓度", type: "number" },
    column20: { text: "劲头", type: "number" },
    column21: { text: "流畅", type: "number" },
    column22: { text: "绵长", type: "number" },
    column23: { text: "香气质", type: "number" },
    column24: { text: "香气量", type: "number" },
    column25: { text: "透发性", type: "number" },
    column26: { text: "杂气程度", type: "number" },
    column27: { text: "杂气种类", type: "string" },
    column28: { text: "细腻程度", type: "number" },
    column29: { text: "柔和程度", type: "number" },
    column30: { text: "圆润感", type: "number" },
    column31: { text: "刺激程度", type: "number" },
    column32: { text: "刺激部位", type: "string" },
    column33: { text: "干净程度", type: "number" },
    column34: { text: "不适类型", type: "string" },
    column35: { text: "不适部位", type: "string" },
    column36: { text: "干燥感", type: "number" },
    column37: { text: "甜度", type: "number" },
    column38: { text: "价类", type: "number" },
    column39: { text: "功能", type: "string" },
    column40: { text: "品牌", type: "string" },
    column41: { text: "品类", type: "string" },
  };
  const errorNum = ref(0);
  const file = ref();
  const percentage = ref(0);
  const showUploadTable = async (ev) => {
    //每次选择文件都把之前文件清空
    uploadTableData.value = [];
    errorNum.value = 0;
    file.value = ev.raw; //这里面就是数据
    // 将file变成二进制读取到的
    let data = await readFileAsBinaryString(file.value);
    // 将得到的二进制转化一下
    let workbook = XLSX.read(data, { type: "binary" });
    // console.log("workbook", workbook); //这里就是可读取的文件了
    // 最后把数据转成json格式的
    let worksheet = workbook.Sheets[workbook.SheetNames[0]]; //这里是表格的名字,这里取第一个表格,1就是第二个表格数据
    // console.log("worksheet", worksheet);
    //将得到的worksheet转化为json格式
    data = XLSX.utils.sheet_to_json(worksheet);
    //循环遍历得到的数据，将传入的字段更改为后台需要的字段
    data.forEach((item) => {
      let obj = {};
      for (let key in characters) {
        let temp = characters[key], //变量只能用[]来访问
          text = temp.text,
          type = temp.type;
        let value = item[text];
        if (value) {
          // if (testStr(value)) {
          //   value = "*****";
          //   errorNum.value++;
          // } else {
          if (type == "string") {
            value = String(value);
          } else if (type == "number") {
            value = Number(value);
          }
          // }
        }
        obj[key] = value;
      }
      uploadTableData.value.push(obj);
      percentage.value = (uploadTableData.value.length / data.length) * 100;
    }
    );
    //获取表格数据
    if (baseData.value == 1) {
      //基础信息
      baseTableData.value = uploadTableData.value;
      console.log("baseTableData.value=", baseTableData.value);
    } else {
      //详细信息
      detailTableData.value = uploadTableData.value;
      console.log("detailTableData.value=", detailTableData.value);
    }
    if (errorNum.value > 0) {
      ElMessage.error("导入数据存在问题，请仔细检查后再导入");
    }
  };
  //单料烟详细数据上传请求
  const uploadDetailInfo = async () => {
    //真正需要上传的时file.value
    const formData = new FormData();
    console.log(file.value);
    formData.append("file", file.value);
    const res = await uploadDetaiInfoService(formData);
    //更新表格和rfid号
    gettobaccos();
    //这里需要异步等待才可以
    await getAllRfids();
    //getOverview();
    // getYearData();
    // getLocationData();
    ElMessage.success(res.message);
  };

  const submitUpload = async () => {
    //将表格数据转化为formData格式的数据
    const formData = new FormData();
    formData.append("file", file.value);
    //将formData传递给后端
    if (baseData.value == 0) {
      uploadDetailInfo(formData);
    } else {
      console.log("上传基本数据表请求");
    }
    uploadTableData.value = [];
    baseTableData.value = [];
    detailTableData.value = [];
    uploadDraw.value = false;
  };

  //上传文件的清除
  const delUpload = () => {
    if (baseTableData.value.length) {
      baseTableData.value = [];
    }
    if (detailTableData.value.length) {
      detailTableData.value = [];
    }
    errorNum.value = 0;
  };

  //============================================================================

  //文件导出
  const downLoadData = () => {
    const idStr = getInfo(ids);
    window.open(
      "http://localhost:8080/tobacco/download?Authorization=" +
        userInfo.value.token +
        "&year=" +
        queryData.value.year +
        "&location=" +
        queryData.value.location +
        "&part=" +
        queryData.value.part +
        "&evaluate=" +
        queryData.value.evaluate +
        "&ids=" +
        idStr
    );
    ids = [];
    tobTable.value.clearSelection();
  };
  //模拟不足登记
  const recordShort = async () => {
    const res = await tobaccoShortService(rfids);
    //将结果保存在shortList中
    res.data.forEach((item) => {
      shortList.value.push(item);
    });
    rfids = [];
    tobTable.value.clearSelection();
    ElMessage.success("登记成功");
  };
  return {
    queryData,
    loading,
    commentVisible,
    infoChecked,
    drawerVisible,
    drawerTitle,
    tobTable,
    detailInfo,
    isSearch,
    showTobaccoPlace,
    addDrawerVisible,
    addTobaccoData,
    addTobaccRules,
    addForm,
    isAddTob,
    addTitle,
    uploadDraw,
    uploadTableData,
    baseTableData,
    detailTableData,
    percentage,
    rfidInfo,
    downLoadData,
    openUploadDraw,
    submitUpload,
    delUpload,
    showUploadTable,
    multipleChoice,
    searchByrfids,
    infoCheckedChange,
    changeComment,
    closeDialog,
    clearQueryData,
    clearAddData,
    tobSizeChange,
    tobPageChange,
    tobDelete,
    submitComment,
    submitQuery,
    submitEvent,
    submitAddTobacco,
    addTobacco,
    replace,
    tobEdit,
    baseTobEdit,
    recordShort,
    //请求服务相关
    gettobaccos,
  };
});
